//
//  LWTabBarController.m
//  1.28 十二期微博
//  Created by mac on 15/1/28.
//  Copyright (c) 2015年 mac. All rights reserved.
//

#import "LWTabBarController.h"
#import "LWTabBarCustom.h"
#import "LWDiscoverViewController.h"
#import "LWHomeViewController.h"
#import "LWMessageViewController.h"
#import "LWMeViewController.h"
#import "LWNavController.h"
#import "LWComposeController.h"
#import "AFNetworking.h"
#import "LWAccount.h"
#import "MJRefresh.h"
#import "LWNetWorkTools.h"
#import "LWUnReadCount.h"
@interface LWTabBarController () <tabBarCustomDelegate>

@property (nonatomic,weak) LWTabBarCustom *customTabbar;
@property (nonatomic,weak) LWHomeViewController *home;
@end

@implementation LWTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTabBar];
    
    LWAccount *account = [LWAccount accountFromSandBox];
    if (account != nil) {
      [self setUpTimer];
    }


}

#pragma mark - 开启定时器获取未读数
- (void)setUpTimer{

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(getUnread) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
- (void)getUnread
{
    
    [[LWNetWorkTools shareNetWorkTools] loadUnreadCount:^(LWUnReadCount *unReadCount) {
        
        // 设置tabbarbutton上的提醒
        self.home.tabBarItem.badgeValue = [unReadCount.status description];
        // 设置图标上的提醒下
        [UIApplication sharedApplication].applicationIconBadgeNumber = [unReadCount.status integerValue];
        
    } failure:^(NSError *error) {
        LWLog(@"%@", error);
    }];
    
}
#pragma mark - 初始化选项卡
- (void)setupTabBar{
    
    //创建自定义的tabbar
    LWTabBarCustom *tabbar = [[LWTabBarCustom alloc] init];
    tabbar.backgroundColor = [UIColor whiteColor];
    tabbar.delegata = self;
    tabbar.frame = self.tabBar.bounds;
    [self.tabBar addSubview:tabbar];
    self.customTabbar = tabbar;
    
}

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    for (UIView *child in self.tabBar.subviews) {
        if ([child isKindOfClass:[UIControl class]]) {
            [child removeFromSuperview];
        }
    }
}

#pragma mark - 初始化选项卡
// init方法内部会调用initWithNibName方法, 所以在自定义控制器时可以把初始化的代码放到initWithNibName方法中, 以后无论是通过init方法还是通过initWithNibName都可以初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        LWHomeViewController *home = (LWHomeViewController *)[self addChildViewWithControllerName:@"LWHomeViewController" withTitle:@"首页" image:@"tabbar_home"selectedImage:@"tabbar_home_highlighted"];
        self.home = home;
        
        [self addChildViewWithControllerName:@"LWMessageViewController" withTitle:@"消息" image:@"tabbar_message_center"selectedImage:@"tabbar_message_center_highlighted"];
        
        
        [self addChildViewWithControllerName:@"LWDiscoverViewController" withTitle:@"发现" image:@"tabbar_discover"selectedImage:@"tabbar_discover_highlighted"];
        
        
        [self addChildViewWithControllerName:@"LWMeViewController" withTitle:@"我" image:@"tabbar_profile"selectedImage:@"tabbar_profile_highlighted"];

    }
    return self;
}

- (UIViewController *)addChildViewWithControllerName:(NSString *)VCName withTitle:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectImage{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:VCName bundle:nil];
    UIViewController *vc = [sb instantiateInitialViewController];
    
   return  [self addChildViewWithController:vc withTitle:title image:image selectedImage:selectImage];
}

- (UIViewController *)addChildViewWithController:(UIViewController *)childVc withTitle:(NSString *)title image:(NSString *)image selectedImage:(NSString *)selectImage{
    
   // childVc.view.backgroundColor = IWRandomColor;
    childVc.title = title;
    childVc.tabBarItem.image = [UIImage imageNamed:image];
    //创建图片
    UIImage *newImg = [UIImage imageNamed:selectImage];
    newImg = [newImg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childVc.tabBarItem.selectedImage = newImg;
    [childVc.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor]} forState:UIControlStateSelected];
    //创建导航控制器
    LWNavController *nav = [[LWNavController alloc] initWithRootViewController:childVc];
    
    [self addChildViewController:nav];
    [self.customTabbar addItme:childVc.tabBarItem];
    return childVc;
}

#pragma mark - tabBarCustom的代理

- (void)tabBarCustom:(LWTabBarCustom *)tabbar from:(NSInteger)from to:(NSInteger)to{
    self.selectedIndex = to;
    
    //取出home控制器
    UINavigationController *nav = self.childViewControllers[to];
    UIViewController *vc = [nav topViewController];
    if ([vc isKindOfClass:[LWHomeViewController class]]) {
        if (from == 0 && to == 0) {
            if (self.home.tabBarItem.badgeValue.intValue > 0) {
                [self.home.tableView headerBeginRefreshing];
            }else{
                NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
                [self.home.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
            }
        }
    }
}

- (void)tabBarCustom:(LWTabBarCustom *)tabbar selectplusBtn:(UIButton *)plusBtn{
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"LWComposeController" bundle:nil];
    LWComposeController *compose = [sb instantiateInitialViewController];
    LWNavController *navVc = [[LWNavController alloc] initWithRootViewController:compose];
    [self presentViewController:navVc animated:YES completion:nil];
}

@end
